<template>
  <div class="page-articleAlbum">
    <filter-view @update-list="getAlbumList()" />
    <a-table
      id="sortTable"
      :row-selection="{ selectedRowKeys: statusState.selectedRowKeys, checkStrictly: false, onChange: onSelectChange }"
      :expandRowByClick="false"
      row-key="album_id"
      :pagination="false"
      :columns="columns"
      :data-source="state.albumList"
      :loading="state.loading"
      :scroll="{ x: 1500 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-else-if="column.key === 'album_name'">
          <a-tooltip placement="top" color="#fff" v-if="record.album_name">
            <template #title>
              {{ record.album_name }}
            </template>
            <div class="ellipsis-text">{{ record.album_name }}</div>
          </a-tooltip>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'album_picture_count'">
          <span>
            {{ formatNumber(record.album_picture_count) }}
          </span> </template
        ><template v-else-if="column.key === 'created_at'">
          <span>
            {{ formatToDateTime(record.created_at * 1000) }}
          </span>
        </template>
        <template v-else-if="column.key === 'album_status'">
          <span>
            <a-switch
              v-model:checked="record.album_status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="articleManagement(record)">管理文章</a>
            <a-divider type="vertical" />
            <a class="basicColor" @click="updateAlbum(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="basicColor" @click="deleteAlbum(record)">删除</a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 删除对话框 -->
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该专辑吗</span>
    </modal-view>
    <!-- 新建专辑对话框 -->
    <modal-view
      :title="statusState.isAdd ? '新建专辑' : '编辑专辑'"
      v-model:visible="statusState.addClassify"
      okText="确定"
      cancelText="取消"
      :afterClose="() => formRef.resetFields()"
      @confirm="addConfirm"
      @cancel="addCancel"
      :width="511"
    >
      <a-form ref="formRef" :model="addFormState" :rules="addFormRules">
        <a-form-item label="专辑名称" name="album_name">
          <a-input
            v-model:value.trim="addFormState.album_name"
            :maxlength="30"
            class="w-[359px]"
            placeholder="请输入专辑名称"
          />
        </a-form-item>
        <a-form-item label="设定价格" name="album_price_type">
          <a-radio-group v-model:value="addFormState.album_price_type" @change="handleChange">
            <a-radio :value="1">原价</a-radio>
            <a-radio :value="2" class="ml-[32px]" disabled>固定价格</a-radio>
            <a-radio :value="3" class="ml-[32px]" disabled>随机价格</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item name="album_price_copy" v-if="addFormState.album_price_type === 2" style="margin-left: 80px">
          <a-input
            v-model:value="addFormState.album_price_copy"
            class="w-[359px]"
            placeholder="请输入固定金币数，不填或0为免费"
            suffix="金币"
          />
        </a-form-item>
        <a-form-item name="album_price_copy" v-if="addFormState.album_price_type === 3" style="margin-left: 80px">
          <a-input
            v-model:value="addFormState.album_price_copy"
            class="w-[359px]"
            placeholder="请输入多个随机金币 ,使用逗号“,”分隔"
            suffix="金币"
          />
        </a-form-item>
        <a-form-item label="专辑状态" name="album_status">
          <a-radio-group v-model:value="addFormState.album_status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="2" class="ml-[32px]">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </modal-view>
    <!-- <ArticleManagementDialog
      v-model:visible="articleVisible"
      :title="articleName"
      :albumId="albumId"
      okText="确定"
      cancelText="取消"
      :width="1200"
      @confirm="handleOk"
      @cancel="handleCancel"
    /> -->
    <AlbumManage
      v-model:visible="articleVisible"
      :albumId="albumId"
      :title="articleName"
      :width="1296"
      type="文章"
      :left-api-path="article_list"
      :right-api-path="article_get_album_article"
      :class-api-path="article_classify_list"
      :add-api-path="article_add_album_article"
      :del-api-path="article_del_album_article"
      @refresh-list="() => getAlbumList()"
      @confirm="handleOk"
      @cancel="() => (articleVisible = false)"
    />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { formatNumber, formatToDateTime } from '@/utils/format'
import Sortable from 'sortablejs'
import FilterView from './components/FilterView.vue'
import { column } from './dataSource'
import type { ArticleAlbumData } from '@/types/site/article/articleAlbum'
import { albumState, statusState } from './state'
import AlbumManage from './components/album-manage/albumManage.vue'
import ModalView from '@/components/components/modal/ModalView.vue'
import ArticleManagementDialog from './components/ArticleManagementDialog.vue'
import apis from '@/apis'
import { storage } from '@/utils/storage'
const {
  site: {
    article_list,
    article_classify_list,
    article_add_album_article,
    article_get_album_article,
    article_del_album_article,
    article_album_list,
    edit_status,
    article_filter_classify_list,
    article_add_album,
    article_update_album,
    article_del_album
  }
} = apis
const columns = ref(column)
const siteId = storage.get('siteId')
const deleteVisible = ref(false)
const formRef = ref()
type Key = string
const state = reactive<{ loading: boolean; albumList: ArticleAlbumData[] }>({
  loading: false,
  albumList: [] as ArticleAlbumData[]
})
const articleName = ref('') //专辑名称
const albumId = ref('') //专辑id
const deleteId = ref('') //删除专辑id
const articleVisible = ref(false)
//新建专辑
interface IState {
  album_id?: string
  album_name: string
  album_price_type: number
  album_status: number
  album_price_copy: string
  album_order?: string
  album_price: number[]
  site_id?: string
}
const addFormState = reactive<IState>({
  album_name: '',
  album_price_type: 1, //设定价格
  album_status: 1,
  album_price_copy: '',
  album_price: []
})
const reg = /^((\d){1,6})((\,\d{1,6})+)?$/
const reg2 = /^[0-9]{1,6}$/
const validatePrice = (rule: any, value: any, callback: any) => {
  if (!value) {
    return Promise.resolve()
  } else {
    if (addFormState.album_price_type === 2) {
      if (!reg2.test(value)) return Promise.reject('请输入0-999999的整数')
      return Promise.resolve()
    } else {
      if (!reg.test(value)) return Promise.reject('请输入0-999999的整数，多个金币使用英文逗号隔开')
      return Promise.resolve()
    }
  }
}
const addFormRules = reactive({
  album_name: [{ required: true, message: '请输入专辑名称' }],
  album_price_type: [{ required: true, message: '请设定价格' }],
  album_price_copy: [{ required: false, validator: validatePrice, trigger: 'blur' }]
})
//获取专辑接口
const getAlbumList = () => {
  state.loading = true
  albumState.site_id = siteId
  if (!albumState.album_id) albumState.album_id = undefined
  article_album_list(albumState)
    .then((res: any) => {
      state.albumList = res?.albums ?? []
      state.loading = false
      console.log('专辑列表: ', state.albumList)
    })
    .catch(() => {
      state.loading = false
    })
}
const handleChange = () => {
  addFormState.album_price_copy = ''
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
const deleteAlbum = (item: ArticleAlbumData) => {
  console.log(12321)
  deleteVisible.value = true
  deleteId.value = item.album_id
}
//管理文章
const articleManagement = (item: ArticleAlbumData) => {
  console.log('item: ', item)
  articleVisible.value = true
  albumId.value = item.album_id
  articleName.value = item.album_name + '-管理文章'
}
//编辑
const updateAlbum = (item: ArticleAlbumData) => {
  console.log('item: ', item)
  statusState.addClassify = true
  statusState.isAdd = false
  const { created_at, album_popularity, album_article_count, album_price, ...params } = item
  Object.assign(addFormState, params)
  addFormState.album_price_copy = album_price.join(',')
  console.log('addFormState: ', addFormState)
}
const editStatus = (checked: number, row: ArticleAlbumData) => {
  const data = {
    type: 8,
    status: checked,
    id: [row.album_id]
  }
  edit_status(data).then(() => {
    message.success(checked === 1 ? '启用成功' : '禁用成功')
    getAlbumList()
  })
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  article_del_album({ album_id: [deleteId.value] }).then(() => {
    message.success('文章专辑删除成功')
    deleteVisible.value = value
    getAlbumList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
//提交前数据处理
const dataDeal = () => {
  if (addFormState.album_price_copy) {
    if (addFormState.album_price_type === 1) {
      addFormState.album_price = []
    } else if (addFormState.album_price_type === 2) {
      addFormState.album_price = [+addFormState.album_price_copy]
    } else {
      if (addFormState.album_price_copy.indexOf(',') != -1) {
        const arr: number[] = []
        addFormState.album_price_copy.split(',').map((item: string): number[] => {
          arr.push(+item)
          return arr
        })
        addFormState.album_price = arr
      } else {
        addFormState.album_price = [+addFormState.album_price_copy]
      }
    }
  } else {
    addFormState.album_price = [0]
  }
}
/**
  新建/编辑分类对话框事件
 */
const addConfirm = (value: any) => {
  formRef.value.validate().then(() => {
    console.log(addFormState)
    if (statusState.isAdd) {
      addFormState.site_id = siteId
      dataDeal()
      const { album_price_copy, ...params } = addFormState
      article_add_album(params).then(() => {
        message.success('新建文章专辑成功')
        statusState.addClassify = value
        getAlbumList()
      })
    } else {
      dataDeal()
      const { album_price_copy, album_order, ...params } = addFormState
      article_update_album(params).then(() => {
        message.success('编辑文章专辑成功')
        statusState.addClassify = value
        getAlbumList()
      })
    }
  })
}
const addCancel = () => {
  formRef.value.resetFields() //关闭弹窗清空表单
  statusState.addClassify = false
}
const handleOk = () => {
  articleVisible.value = false
  getAlbumList()
}
const handleCancel = () => {
  articleVisible.value = false
}
//调用排序接口
const sortFunc = (item: any) => {
  article_update_album({
    ...item
  }).then(() => {
    message.success('编辑成功')
    getAlbumList()
  })
}
//初始化表格拖动
const initSortable = () => {
  const el = document.querySelector('#sortTable tbody') as HTMLElement
  console.log({ el })
  new Sortable(el, {
    handle: '.ant-table-row',
    animation: 150,
    ghostClass: 'blue-background-class',
    forceFallback: true,
    sort: true,
    // async
    onEnd(item) {
      console.log({ item })
      if (item.newIndex === item.oldIndex) return
      const startIndex = (item.oldIndex as number) - 1
      const endIndex = (item.newIndex as number) - 1
      const { album_order, ...params } = state.albumList[startIndex]
      // params.album_order = state.albumList[endIndex].album_order
      sortFunc({ album_order: state.albumList[endIndex].album_order, ...params })
    }
  })
}
onMounted(() => {
  getAlbumList()
  initSortable()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;

:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.page-articleAlbum {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
